<template>
  <div class="exam-container">
    <el-tabs v-model="activeTab" class="exam-tabs">
      <el-tab-pane label="题库管理" name="question-bank">
        <div class="question-bank">
          <div class="toolbar">
            <el-button type="primary" @click="showAddQuestionDialog">
              <el-icon><Plus /></el-icon> 新增题目
            </el-button>
          </div>

          <div class="questions-list">
            <el-card v-for="question in questions" :key="question.id" class="question-card">
              <template #header>
                <div class="question-header">
                  <span class="question-title">{{ question.title }}</span>
                  <div class="question-actions">
                    <el-button type="primary" link @click="editQuestion(question)">
                      <el-icon><Edit /></el-icon> 编辑
                    </el-button>
                    <el-button type="danger" link @click="deleteQuestion(question.id)">
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </div>
                </div>
              </template>
              <div class="question-content">
                <div class="question-type">
                  <el-tag :type="getQuestionTypeTag(question.type)">
                    {{ getQuestionTypeLabel(question.type) }}
                  </el-tag>
                </div>
                <div class="question-description">{{ question.description }}</div>
                <div class="question-options" v-if="question.type === 'choice'">
                  <div v-for="(option, index) in question.options" :key="index" class="option">
                    {{ String.fromCharCode(65 + index) }}. {{ option }}
                  </div>
                </div>
                <div class="question-answer">
                  <strong>答案：</strong>
                  <template v-if="question.type === 'choice'">
                    {{ String.fromCharCode(65 + question.answer) }}
                  </template>
                  <template v-else>
                    {{ question.answer }}
                  </template>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="开始考试" name="exam-start">
        <div class="exam-start">
          <div v-if="!isExamStarted" class="exam-intro">
            <h2>开始考试</h2>
            <el-form :model="examConfig" label-width="100px">
              <el-form-item label="考试时长">
                <el-input-number v-model="examConfig.duration" :min="30" :max="180" :step="30" />
                <span class="unit">分钟</span>
              </el-form-item>
              <el-form-item label="题目数量">
                <el-input-number v-model="examConfig.questionCount" :min="5" :max="50" :step="5" />
                <span class="unit">题</span>
              </el-form-item>
              <el-form-item label="题目类型">
                <el-checkbox-group v-model="examConfig.questionTypes">
                  <el-checkbox label="choice">选择题</el-checkbox>
                  <el-checkbox label="fill">填空题</el-checkbox>
                  <el-checkbox label="essay">问答题</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
            <el-button type="primary" @click="startExam" :disabled="loadingQuestions">开始考试</el-button>
          </div>

          <div v-else class="exam-content">
            <div class="exam-header">
              <div class="exam-info">
                <h2>前端开发考试</h2>
                <div class="exam-progress">
                  进度：{{ currentQuestionIndex + 1 }}/{{ examQuestions.length }}
                </div>
              </div>
              <div class="exam-timer">
                剩余时间：{{ formatTime(remainingTime) }}
              </div>
            </div>

            <div class="question-area">
              <div class="question-navigation">
                <el-button
                  v-for="(q, index) in examQuestions"
                  :key="index"
                  :type="getQuestionButtonType(index)"
                  @click="goToQuestion(index)"
                >
                  {{ index + 1 }}
                </el-button>
              </div>

              <div class="current-question">
                <div class="question-title">
                  {{ currentQuestionIndex + 1 }}. {{ currentQuestion.title }}
                </div>
                <div class="question-description">
                  {{ currentQuestion.description }}
                </div>

                <div class="question-options" v-if="currentQuestion.type === 'choice'">
                  <el-radio-group v-model="userAnswers[currentQuestionIndex]">
                    <el-radio
                      v-for="(option, index) in currentQuestion.options"
                      :key="index"
                      :label="index"
                    >
                      {{ String.fromCharCode(65 + index) }}. {{ option }}
                    </el-radio>
                  </el-radio-group>
                </div>

                <div class="question-options" v-else-if="currentQuestion.type === 'fill'">
                  <el-input
                    v-model="userAnswers[currentQuestionIndex]"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入答案"
                  />
                </div>

                <div class="question-options" v-else-if="currentQuestion.type === 'essay'">
                  <el-input
                    v-model="userAnswers[currentQuestionIndex]"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入答案"
                  />
                </div>

                <div class="question-actions">
                  <el-button
                    v-if="currentQuestionIndex > 0"
                    @click="goToQuestion(currentQuestionIndex - 1)"
                  >
                    上一题
                  </el-button>
                  <el-button
                    v-if="currentQuestionIndex < examQuestions.length - 1"
                    type="primary"
                    @click="goToQuestion(currentQuestionIndex + 1)"
                  >
                    下一题
                  </el-button>
                  <el-button
                    v-else
                    type="success"
                    @click="submitExam"
                  >
                    提交试卷
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增/编辑题目对话框 -->
    <el-dialog
      v-model="questionDialog.visible"
      :title="questionDialog.isEdit ? '编辑题目' : '新增题目'"
      width="50%"
    >
      <el-form :model="questionDialog.form" label-width="100px">
        <el-form-item label="题目类型">
          <el-select v-model="questionDialog.form.type">
            <el-option label="选择题" value="choice" />
            <el-option label="填空题" value="fill" />
            <el-option label="问答题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目">
          <el-input v-model="questionDialog.form.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="questionDialog.form.description" />
        </el-form-item>
        <el-form-item v-if="questionDialog.form.type === 'choice'" label="选项">
          <div v-for="(option, index) in questionDialog.form.options" :key="index" class="option-item">
            <el-input v-model="questionDialog.form.options[index]" />
            <el-button type="danger" link @click="removeOption(index)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          <el-button type="primary" link @click="addOption">
            <el-icon><Plus /></el-icon> 添加选项
          </el-button>
        </el-form-item>
        <el-form-item label="答案">
          <template v-if="questionDialog.form.type === 'choice'">
            <el-select v-model="questionDialog.form.answer">
              <el-option
                v-for="(option, index) in questionDialog.form.options"
                :key="index"
                :label="String.fromCharCode(65 + index)"
                :value="index"
              />
            </el-select>
          </template>
          <template v-else>
            <el-input type="textarea" v-model="questionDialog.form.answer" />
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="questionDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveQuestion">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'

// 标签页
const activeTab = ref('question-bank')

// 题库管理
const questions = ref([])
const loadingQuestions = ref(true)

// 拉取题库
const fetchQuestions = async () => {
  loadingQuestions.value = true
  const res = await fetch('/api/exam/questions')
  const data = await res.json()
  questions.value = data.questions || []
  loadingQuestions.value = false
}

// 题目对话框
const questionDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    type: 'choice',
    title: '',
    description: '',
    options: [''],
    answer: ''
  }
})

// 显示新增题目对话框
const showAddQuestionDialog = () => {
  questionDialog.isEdit = false
  questionDialog.form = {
    type: 'choice',
    title: '',
    description: '',
    options: [''],
    answer: ''
  }
  questionDialog.visible = true
}

// 编辑题目
const editQuestion = (question) => {
  questionDialog.isEdit = true
  // 深拷贝，防止直接修改 questions
  questionDialog.form = JSON.parse(JSON.stringify(question))
  questionDialog.visible = true
}

// 删除题目
const deleteQuestion = async (id) => {
  ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    await fetch(`/api/exam/questions/${id}`, { method: 'DELETE' })
    ElMessage.success('删除成功')
    fetchQuestions()
  })
}

// 添加选项
const addOption = () => {
  questionDialog.form.options.push('')
}

// 删除选项
const removeOption = (index) => {
  questionDialog.form.options.splice(index, 1)
}

// 保存题目
const saveQuestion = async () => {
  const form = questionDialog.form
  if (questionDialog.isEdit) {
    await fetch(`/api/exam/questions/${form.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form)
    })
    ElMessage.success('编辑成功')
  } else {
    await fetch('/api/exam/questions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form)
    })
    ElMessage.success('添加成功')
  }
  questionDialog.visible = false
  fetchQuestions()
}

// 获取题目类型标签
const getQuestionTypeTag = (type) => {
  const tags = {
    choice: 'success',
    fill: 'warning',
    essay: 'info'
  }
  return tags[type] || 'info'
}

// 获取题目类型标签文本
const getQuestionTypeLabel = (type) => {
  const labels = {
    choice: '选择题',
    fill: '填空题',
    essay: '问答题'
  }
  return labels[type] || '未知类型'
}

// 考试配置
const examConfig = reactive({
  duration: 60,
  questionCount: 20,
  questionTypes: ['choice', 'fill', 'essay']
})

// 考试状态
const isExamStarted = ref(false)
const examQuestions = ref([])
const currentQuestionIndex = ref(0)
const userAnswers = ref([])
const remainingTime = ref(0)
let examTimer = null

// 开始考试
const startExam = async () => {
  if (questions.value.length === 0) {
    await fetchQuestions()
    if (questions.value.length === 0) {
      ElMessage.error('题库为空，无法开始考试')
      return
    }
  }
  // 根据配置生成考试题目
  examQuestions.value = questions.value
    .filter(q => examConfig.questionTypes.includes(q.type))
    .sort(() => Math.random() - 0.5)
    .slice(0, examConfig.questionCount)

  userAnswers.value = new Array(examQuestions.value.length).fill('')
  currentQuestionIndex.value = 0
  remainingTime.value = examConfig.duration * 60
  isExamStarted.value = true

  // 开始计时
  examTimer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      submitExam()
    }
  }, 1000)
}

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 获取当前题目
const currentQuestion = computed(() => {
  return examQuestions.value[currentQuestionIndex.value] || {}
})

// 跳转到指定题目
const goToQuestion = (index) => {
  currentQuestionIndex.value = index
}

// 获取题目按钮类型
const getQuestionButtonType = (index) => {
  if (index === currentQuestionIndex.value) {
    return 'primary'
  }
  if (userAnswers.value[index] !== '') {
    return 'success'
  }
  return 'default'
}

// 提交试卷
const submitExam = () => {
  clearInterval(examTimer)
  ElMessageBox.confirm('确定要提交试卷吗？', '提示', {
    type: 'warning'
  }).then(() => {
    // 计算得分
    const score = examQuestions.value.reduce((total, question, index) => {
      if (question.type === 'choice') {
        return total + (userAnswers.value[index] === question.answer ? 1 : 0)
      }
      return total
    }, 0)

    ElMessageBox.alert(`考试结束！\n得分：${score}/${examQuestions.value.length}`, '考试结果', {
      confirmButtonText: '确定',
      callback: () => {
        isExamStarted.value = false
      }
    })
  })
}

// 页面加载时拉取题库
fetchQuestions()
</script>

<style scoped>
.exam-container {
  width: 90vw;
  max-width: 1100px;
  margin: 0 auto;
  height: 100%;
  margin-top: 0;
}

.exam-tabs {
  height: 100%;
}

.question-bank {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.questions-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.question-card {
  height: 100%;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-title {
  font-weight: bold;
}

.question-actions {
  display: flex;
  gap: 10px;
}

.question-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.question-type {
  margin-bottom: 10px;
}

.question-description {
  color: #666;
  margin-bottom: 10px;
}

.question-options {
  margin-bottom: 10px;
}

.option {
  margin-bottom: 5px;
}

.question-answer {
  color: #409EFF;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.exam-start {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 480px;
  width: 100%;
}

.exam-intro {
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 4px 24px 0 rgba(30, 60, 90, 0.10);
  padding: 48px 56px 40px 56px;
  width: 1100px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.exam-intro h2 {
  font-size: 26px;
  font-weight: 900;
  color: #222;
  margin-bottom: 32px;
  text-align: center;
}

.exam-intro .el-form {
  width: 100%;
  margin-bottom: 32px;
}

.exam-intro .el-form-item {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}

.exam-intro .el-form-item__label {
  font-size: 16px;
  color: #222;
  font-weight: 500;
  width: 90px;
  text-align: left;
  padding-right: 8px;
}

.exam-intro .el-input-number {
  width: 110px;
}

.exam-intro .unit {
  margin-left: 8px;
  color: #8a99b3;
  font-size: 15px;
}

.exam-intro .el-checkbox-group {
  display: flex;
  gap: 18px;
}

.exam-intro .el-checkbox {
  font-size: 15px;
  color: #2563eb;
  font-weight: 500;
}

.exam-intro .el-button[type='primary'] {
  width: 100%;
  height: 48px;
  font-size: 18px;
  font-weight: 700;
  border-radius: 12px;
  background: #2563eb;
  border: none;
  box-shadow: 0 2px 8px rgba(37,99,235,0.08);
  margin-top: 8px;
}

.exam-intro .el-button[type='primary']:hover {
  background: #1746a2;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.exam-info h2 {
  margin: 0 0 10px 0;
}

.exam-progress {
  color: #666;
}

.exam-timer {
  font-size: 20px;
  color: #409EFF;
}

.question-area {
  display: flex;
  gap: 20px;
}

.question-navigation {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 200px;
}

.current-question {
  flex: 1;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.question-description {
  color: #666;
  margin-bottom: 20px;
}

.question-options {
  margin-bottom: 20px;
}

.question-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.exam-content {
  width: 1100px;
  margin: 0 auto;
}

.exam-layout {
  width: 1100px;
  max-width: 100%;
  margin: 0 auto;
}
</style> 